package com.yayan.beautyclub.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import com.mysql.jdbc.Statement;
import com.yayan.beautyclub.bean.Keep;

public class KeepDao extends ConnectionBase implements IKeepDao {

	public KeepDao(){}
	
	@Override
	public List<Map<String, Object>> getKeepByUserId(long uId, int page, int size) throws Exception {
		// TODO Auto-generated method stub
		String sqlStr = "select kId,pId,pName,price,images,kTime from keep,product"
				+ " where keep.pId=product.pId and uId=?";
		QueryRunner qRunner = new QueryRunner();
		List<Map<String, Object>> list = qRunner.query(getConn(), sqlStr, new MapListHandler(), uId);
		return list;
	}

	@Override
	public Map<String, Object> getKeepByKeepId(long kId) throws Exception {
		// TODO Auto-generated method stub
		String sqlStr = "select kTime,pName,price,description,cId,images,cName from keep,products,category"
				+ " where kId=? and keep.pId=products.pId and products.cId=category.cId";
		QueryRunner qRunner = new QueryRunner();
		Map<String, Object> map = qRunner.query(getConn(), sqlStr, new MapHandler(), kId);
		return map;
	}

	@Override
	public long save(Keep keep) throws Exception {
		// TODO Auto-generated method stub
		String sqlStr = "insert into keep(pId,uId,kTime) values(?,?,?)";
		Connection conn = getConn();
		conn.setAutoCommit(false);
		PreparedStatement ps = conn.prepareStatement(sqlStr, Statement.RETURN_GENERATED_KEYS);
		ps.setLong(1, keep.getpId());
		ps.setLong(2, keep.getuId());
		//ps.setDate(3, new java.sql.Date(keep.getkTime().getTime()));
		ps.setString(3, new java.sql.Timestamp(keep.getkTime().getTime()).toString());
		int re = ps.executeUpdate();
		ResultSet rsKey = ps.getGeneratedKeys();
		long r = 0;
		while(re != 0 && rsKey.next()){
			r = rsKey.getLong(1);
		}
		conn.commit();
		conn.setAutoCommit(true);
		close(conn,ps,null);
		return r;
	}

	@Override
	public boolean delete(long kId) throws Exception {
		// TODO Auto-generated method stub
		String sqlStr = "delete from keep where kId=?";
		Connection conn = getConn();
		PreparedStatement ps = conn.prepareStatement(sqlStr);
		ps.setLong(1, kId);
		boolean res = ps.executeUpdate() > 0 ? true : false; 
		close(conn,ps,null);
		return res;
	}

}
